package FrameWork.EventBus;

import FrameWork.Executor.EventLoopThread;

import java.util.function.Consumer;

public class ITask<T> implements Runnable{

    private Emitter emitter;
    private int dispatcherCode;
    private Runnable runnable;
    private Consumer<AsyncResult<T>> consumer;
    private AsyncResult<T> value;

    public static ITask valueOf(Emitter emitter,Runnable runnable){
        ITask task = new ITask();
        task.setEmitter(emitter);
        task.setDispatcherCode(emitter.getDispatcherCode());
        task.setRunnable(runnable);
        return task;
    }

    public static ITask wrap(Runnable r){
        ITask task = new ITask();
        task.runnable = r;
        Thread thread = Thread.currentThread();
        if (thread instanceof EventLoopThread){
            EventLoopThread eventLoopThread = (EventLoopThread)thread;
            task.dispatcherCode = eventLoopThread.getEventLoop().getDispatcherCode();
        }else{
            task.dispatcherCode = -1;
        }
        return task;
    }

    public static <T>ITask<T> wrap(Consumer<AsyncResult<T>> consumer){
        ITask<T> task = new ITask<>();
        task.consumer = consumer;
        return task;
    }

    public AsyncResult<T> getValue() {
        return value;
    }

    public void setValue(AsyncResult<T> value) {
        this.value = value;
    }

    @Override
    public void run() {
        if (runnable!=null){
            runnable.run();
        }
        if (consumer!=null && value!=null){
            consumer.accept(value);
        }
    }

    public Emitter getEmitter() {
        return emitter;
    }

    public void setEmitter(Emitter emitter) {
        this.emitter = emitter;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    public int getDispatcherCode() {
        return dispatcherCode;
    }

    public void setDispatcherCode(int dispatcherCode) {
        this.dispatcherCode = dispatcherCode;
    }
}
